package com.ruoyi.common.utils;


import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class RsaUtils {

    public static final String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMDxuJ8w3GGSEtF/8TK7edc31Kp7pkV2T+Nsy/el61XyLnr2CF7LUwx4XSoOkw7gDmZ+L3q0fpHoNyoAYnjPZj0CAwEAAQ==";
    public static final String PRIVATE_KEY = "MIIBVwIBADANBgkqhkiG9w0BAQEFAASCAUEwggE9AgEAAkEAwPG4nzDcYZIS0X/x\n" +
            "Mrt51zfUqnumRXZP42zL96XrVfIuevYIXstTDHhdKg6TDuAOZn4verR+keg3KgBi\n" +
            "eM9mPQIDAQABAkEAp13GyYgn0xdT7ZjvEBPiB9etSUlDHQQZHm1UrPinIIAXKRN3\n" +
            "3rG6M/F6KB1KqWSQX0jBlaE53nZ8F5EeuhIk4QIhAOSdFQPzRsPqBCooAALQCD3l\n" +
            "1lg+xR9hS11lTdobDaHlAiEA2A7DLflyFUfXLsW8LeAb7P/NPE5F02G7RqeLAdQ8\n" +
            "TXkCIQCJmZqKlCTlyrbTANxw1PIA/5Ox7aYMKy2He3AOdPYRmQIhALnsGjFZ0r5V\n" +
            "T+rD5adkjyNnDOm0QYohM9MdIhW02R+hAiEAmy3OORt0PK3XqLgi+th2mqKX8D+I\n" +
            "Ts4RWi6W9FqrnhY=";


    /**
     * 使用私钥对数据进行加密签名 (Java API)
     *
     * @param data 数据
     * @return 加密后的签名
     */
    public static String sign1(String data) throws Exception {
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyf.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(PRIVATE_KEY)));
        java.security.Signature signet = java.security.Signature.getInstance("MD5withRSA");
        signet.initSign(privateKey);
        signet.update(data.getBytes("utf-8"));
        byte[] signed = signet.sign();
        return Base64.encode(signed);
    }


    /**
     * RSA 私钥签名
     *
     * @param data 签名数据
     */
    public static String rsaSign(String data) {
        // 将私钥字符串转换成私钥对象
        PrivateKey privateKey = SecureUtil.generatePrivateKey("RSA", Base64.decode(PRIVATE_KEY));
        // 设置签名对象以及加密算法
        Sign sign = SecureUtil.sign(SignAlgorithm.MD5withRSA);
        // 设置私钥，然后执行签名
        sign.setPrivateKey(privateKey);
        byte[] bytes = sign.sign(data.getBytes());
        // 将签名转换为 Base64 字符串，然后返回
        return Base64.encode(bytes);
    }

    /**
     * RSA 公钥验签
     *
     * @param data       签名数据
     * @param signString 签名
     * @return 是否验证成功
     */
    public static boolean rsaSignVerify(String data, String signString) {
        // 将公钥字符串转换成公钥对象
        PublicKey publicKey = SecureUtil.generatePublicKey("RSA", Base64.decode(PUBLIC_KEY));
        // 设置签名对象以及加密算法
        Sign sign = SecureUtil.sign(SignAlgorithm.MD5withRSA);
        // 将签名字符串转换成 byte 数组
        byte[] bytes = Base64.decode(signString);
        // 设置公钥，然后执行验签
        sign.setPublicKey(publicKey);
        boolean isOk = sign.verify(data.getBytes(), bytes);
        System.out.println("签名验证结果：" + isOk);
        return isOk;
    }


}
